﻿using Pay.Dal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.Model;
using Pay.Model.Interfaces;
using Dapper;
using Pay.Dapper;
using Dapper.Contrib.Extensions;
using Pay.Model.Dto;
using Pay.Model.Model;

namespace Pay.DalImplement
{
    public class AliAccountDalImplement : IAliAccountDal
    {

        public async Task<List<QRCodeInfo>> GetByAmount(decimal amount, long[] ids)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "SELECT  [Id],[AliAccountId],[Amount],[Address],[NewAddress],[NewImageName],[QRcodeUrl],[Description],[CreateTime] FROM qrcode_info where AliAccountId in @ids and Amount=@Amount ";

                var data = await conn.QueryAsync<QRCodeInfo>(sql, new { Amount = amount, ids = ids });
                return data.ToList();
            }
        }
        /// <summary>
        /// 根据userID获取关联的支付宝账号
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<AliAccountInfo>> GetAccountByUserId(long userId)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "select [Id],[AccountName],[Pwd],[QRcodeAddres],[IsEnable],[SystemAccount],[ActiveTime],[UserId],[CreateTime],[QRcodeUrl] FROM dbo.aliaccount_info WHERE userId=@userId";
                var data = await conn.QueryAsync<AliAccountInfo>(sql, new { userId = userId });
                return data.ToList();
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<bool> Update(AliAccountInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.UpdateAsync<AliAccountInfo>(model);
            }
        }

        public async Task<long> Add(AliAccountInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.InsertAsync<AliAccountInfo>(model);
            }
        }

        public async Task<long> Add(QRCodeInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.InsertAsync<QRCodeInfo>(model);
            }
        }

        public async Task<bool> Delete(AliAccountInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.DeleteAsync<AliAccountInfo>(model);
            }
        }

        public async Task<bool> Forbidden(AliAccountInfo model)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.UpdateAsync<AliAccountInfo>(model);
            }

        }

        public async Task<AliAccountInfo> GetAccountById(long Id)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {

                string sql = "select Id,AccountName,QRcodeAddres,IsEnable,merchantid,CreateTime,QRcodeUrl,ActiveTime,SystemAccount from aliaccount_info where id=@id";
                return await conn.QueryFirstOrDefaultAsync<AliAccountInfo>(sql, new { id = Id });
            }
        }

        public async Task<IPagedOutput<AliAccountInfo>> GetPage(string searchWord, long userId, DateTime? timeBegin = null, DateTime? timeEnd = null, int offset = 10, int rows = 1)
        {
            StringBuilder sb = new StringBuilder("SELECT Id,AccountName,QRcodeAddres,IsEnable,merchantid,CreateTime,QRcodeUrl,ActiveTime,SystemAccount from aliaccount_info where 1=1");
            DynamicParameters param = new DynamicParameters();
            //param.Add("userId", userId);
            if (!string.IsNullOrWhiteSpace(searchWord))
            {
                sb.Append(" and  AccountName like '%'+@searchWord+'%'");
                param.Add("@searchWord", searchWord);
            }
            if (timeBegin.HasValue && timeEnd.HasValue)
            {
                sb.Append(" and  createtime >=@timeBegin and createTime <=@timeEnd");
                param.Add("@timeBegin", timeBegin.Value);
                param.Add("@timeEnd", timeEnd.Value);

            }

            using (var conn = ConnectionFactory.GetReadConnection())
            {
                return await conn.PagedByAsync<AliAccountInfo>(sb, param, offset, rows, "createTime", false);
            }
        }

        public async Task<bool> IsContainSystemAccount(string systmeName)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {

                string sql = "select * from aliaccount_info where SystemAccount=@SystemAccount";
                return await conn.QueryFirstOrDefaultAsync<AliAccountInfo>(sql, new { SystemAccount = systmeName }) == null ? false : true;

            }
        }

        public async Task<AliAccountInfo> GetInfoBySystemName(string systemName)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {

                string sql = "select * from aliaccount_info where SystemAccount=@SystemAccount";
                return await conn.QueryFirstOrDefaultAsync<AliAccountInfo>(sql, new { SystemAccount = systemName });

            }
        }


        public async Task<MerchantInfo> GetKeyByCode(string code)
        {

            using (var conn = ConnectionFactory.GetReadConnection())
            {

                string sql = "select id, UserId,AppId,AccessKey,MerchantCode,ExpireTime,CreateTime,FeeRate from api_info where MerchantCode=@MerchantCode";
                return await conn.QueryFirstOrDefaultAsync<MerchantInfo>(sql, new { MerchantCode = code });

            }
        }
    }
}
